<style scoped>
.el-pagination {
    margin-top: 20px;
    text-align: center;
}
</style>


<template>
    <el-form @submit.native.prevent :inline="true" :model="roleListQuery" ref="queryForm" class="demo-form-inline">
        <el-form-item label="角色id" prop="roleId">
            <el-input v-model="roleListQuery.roleId" placeholder="角色id" />
        </el-form-item>
        <el-form-item label="角色Key" prop="roleKey">
            <el-input v-model="roleListQuery.roleKey" placeholder="角色Key" />
        </el-form-item>
        <el-form-item label="角色名" prop="roleName">
            <el-input v-model="roleListQuery.roleName" placeholder="角色名" />
        </el-form-item>
        <el-form-item label="状态" prop="disabled">
            <el-select v-model="roleListQuery.disabled" placeholder="状态">
                <el-option label="禁用" :value="true" />
                <el-option label="启用" :value="false" />
            </el-select>
        </el-form-item>
        <el-row>
            <el-form-item>
                <el-button :disabled="tableLoading" type="primary" @click="showCreateDialog">新增</el-button>
                <el-button :disabled="tableLoading" type="primary" native-type="submit"
                    @click="submitQueryList(queryForm)">查询</el-button>
                <el-button :disabled="tableLoading" @click="resetForm(queryForm)">重置</el-button>
            </el-form-item>
        </el-row>

    </el-form>

    <el-table v-loading="tableLoading" :data="roleList" style="width: 100%" border>
        <el-table-column prop="roleId" label="角色id" align="center" />
        <el-table-column prop="roleName" label="角色名" align="center" />
        <el-table-column prop="roleKey" label="角色key" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column prop="disabled" label="状态" align="center">
            <template #default="scope">
                <el-tag :type="scope.row.disabled ? 'danger' : 'success'" disable-transitions>{{ scope.row.disabled ? '禁用' :
                    '启用' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="showDetailDialog(scope.row)">查看</el-button>
                <el-button link type="primary" size="small" @click="showUpdateDialog(scope.row)">编辑</el-button>
                <el-button link :type="scope.row.disabled ? 'success' : 'danger'" size="small"
                    @click="handleUpdateDisabled(scope.row)">{{ scope.row.disabled ? '启用' : '禁用' }}
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination :page-count="pageInfo.pageCount" :page-size="pageInfo.pageSize" :current-page="pageInfo.currentPage"
        :total="pageInfo.pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" background
        layout="total,sizes,prev,pager,next,jumper,->"></el-pagination>


    <el-dialog v-model="detailFormVisible" :title="detailFormTitle" width="300px" center>
        <el-form :model="currentEntity">
            <el-form-item label="角色id" prop="roleId" label-width="100px" disabled>
                <el-input v-model="currentEntity.roleId" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="角色Key" prop="roleKey" label-width="100px">
                <el-input v-model="currentEntity.roleKey" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色名称" prop="roleName" label-width="100px">
                <el-input v-model="currentEntity.roleName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" prop="remark" label-width="100px">
                <el-input v-model="currentEntity.remark" autocomplete="off" />
            </el-form-item>
            <el-form-item label="状态" prop="disabled" label-width="100px">
                <el-select v-model="currentEntity.disabled">
                    <el-option label="禁用" :value="true" />
                    <el-option label="启用" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="权限" prop="authorityIdList" label-width="100px">
                <el-select v-model="currentEntity.authorityIdList" :multiple="true">
                    <el-option v-for="authority in authorityList" :key="authority.authorityId" :label="authority.authorityName"
                        :value="authority.authorityId" />
                </el-select>
            </el-form-item>

        </el-form>
        <template #footer v-if="PageState.DETAIL != currentPageState">
            <span class="dialog-footer">
                <el-button @click="detailFormVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateOrCreate">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { Role } from '@/domain/entity/Role';
import { RoleListQuery } from '@/domain/query/RoleListQuery';
import { reactive, ref, watch } from 'vue';
import * as roleApi from '@/api/RoleApi';
import * as authorityApi from '@/api/AuthorityApi';
import { PageInfo } from "@/domain/entity/PageInfo";
import { Authority } from '@/domain/entity/Authority';
import { Action, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { PageState } from '@/domain/enums/PageState';

// 表格是否在加载
const tableLoading = ref(false);
// 角色列表
const roleList: Array<Role> = reactive<Array<Role>>(new Array());
// 查询表单对象
const queryForm = ref<FormInstance>();
// 分页查询对象
const roleListQuery: RoleListQuery = reactive<RoleListQuery>(new RoleListQuery());
// 当前页面分页信息
const pageInfo: PageInfo = reactive<PageInfo>(new PageInfo())
// 当前对象信息
const currentEntity: Role = reactive<Role>(new Role());
// 当前页面状态
const currentPageState = ref<PageState>(PageState.DETAIL);
// 详情表单标题
const detailFormTitle = ref<string>("详情");
// 详情表单是否展示
const detailFormVisible = ref(false);
// 权限信息列表
const authorityList: Array<Authority> = reactive<Array<Authority>>(new Array());

// 监听当前权限列表
watch(() => currentEntity.authorityList!, (roleList: Array<Authority>) => {
    if (!!roleList) {
        if (!!!currentEntity.authorityIdList) {
            currentEntity.authorityIdList = new Array();
        }
        
        currentEntity.authorityIdList!.length! = 0;
        roleList.forEach((authority, index) => {
            currentEntity.authorityIdList!.push(authority.authorityId!);
        });
    }
});

// 侦听页面大小改变,触发table刷新
watch(() => pageInfo.pageSize, (val) => {
    roleListQuery.size = val;
    updateTable()
})
// 侦听当前页码改变,触发table刷新
watch(() => pageInfo.currentPage, (val) => {
    roleListQuery.current = val;
    updateTable()
})


// 分页插件处理事件
const handleSizeChange = (val: number) => {
    pageInfo.pageSize = val;
}
const handleCurrentChange = (val: number) => {
    pageInfo.currentPage = val
}


/**
* 更新角色列表展示
*/
const updateTable = () => {
    tableLoading.value = true;
    roleApi.getListPage(roleListQuery).then(response => {
        let list: Array<Role> = response.data.data!.records;
        roleList.length = 0;
        roleList.push(...list)
        pageInfo.pageCount = response.data.data?.pages!;
        pageInfo.pageSize = response.data.data?.size!;
        pageInfo.pageTotal = response.data.data?.total!;
        pageInfo.currentPage = response.data.data?.current!;
    }).finally(() => {
        tableLoading.value = false;
    });
}

// 加载完毕之后,更新列表
updateTable();

/**
 * 提交查询表单
 * @param queryFormInstance 查询表单对象
 */
const submitQueryList = (queryFormInstance: FormInstance | undefined) => {
    if (!queryFormInstance) return;
    updateTable();
}

/**
 * 重置查询表单
 * @param queryFormInstance 查询表单对象
 */
const resetForm = (queryFormInstance: FormInstance | undefined) => {
    if (!queryFormInstance) return;
    queryFormInstance.resetFields()
}

/**
 * 更新权限列表
 */
const updateAuthorityList = () => {
    authorityApi.getList().then(response => {
        authorityList.length = 0;
        authorityList.push(...response.data.data!);
    });
}


/**
 * 展示详情对话框
 * @param row 行数据
 */
const showDetailDialog = (row: Role) => {
    currentPageState.value = PageState.DETAIL
    detailFormTitle.value = "详情";
    updateAuthorityList();
    Object.assign(currentEntity, new Role());
    Object.assign(currentEntity, row);
    detailFormVisible.value = true;
    roleApi.getDetail(currentEntity.roleId!).then(response => {
        Object.assign(currentEntity, response.data.data);
    });

}

/**
 * 展示更新对话框
 * @param row 行数据
 */
const showUpdateDialog = (row: Role) => {

    currentPageState.value = PageState.UPDATE;
    detailFormTitle.value = "更新";
    updateAuthorityList();
    Object.assign(currentEntity, new Role());
    Object.assign(currentEntity, row);
    detailFormVisible.value = true;
    roleApi.getDetail(currentEntity.roleId!).then(response => {
        Object.assign(currentEntity, response.data.data);
    });
}

/**
 * 展示新增
 */
const showCreateDialog = () => {
    currentPageState.value = PageState.CREATE;
    detailFormTitle.value = "新增";
    updateAuthorityList();
    Object.assign(currentEntity, new Role());
    currentEntity.disabled = false;
    currentEntity.authorityIdList = new Array;
    currentEntity.authorityList = new Array;
    detailFormVisible.value = true;
}

/**
 * 处理更新或者创建
 */
const handleUpdateOrCreate = () => {

    switch (currentPageState.value) {
        case PageState.CREATE:
            roleApi.create(currentEntity).then(response => {
                let responseRole = response.data.data;
                Object.assign(currentEntity, new Role());
                Object.assign(currentEntity, responseRole);
                updateTable();
                detailFormVisible.value = false;
            });
            break;
        case PageState.UPDATE:
            roleApi.update(currentEntity).then(response => {
                let responseRole = response.data.data;
                Object.assign(currentEntity, new Role());
                Object.assign(currentEntity, responseRole);
                updateTable();
                detailFormVisible.value = false;
            });
            break;
        default:
            break;
    }

}

/**
 * 展示禁用对话框
 * @param row 行数据
 */
const handleUpdateDisabled = (row: Role) => {
    Object.assign(currentEntity, new Role());
    Object.assign(currentEntity, row);

    ElMessageBox({
        title: '切换禁用状态',
        message: `切换禁用状态: ${currentEntity.roleName}(${currentEntity.roleId}) ?`,
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: (action: Action) => {
            if (action === 'confirm') {
                roleApi.updateDisabled(currentEntity.roleId!).then(response => {

                    if (response.data.code === 0) {
                        ElMessage.success('更新成功')
                        updateTable();
                    } else {
                        ElMessage.warning('更新失败')
                    }
                });
            }
        }
    });


}


/**
 * 展示删除对话框
 * @param row 行数据
 */
const handleDelete = (row: Role) => {
    Object.assign(currentEntity, new Role());
    Object.assign(currentEntity, row);
    ElMessageBox({
        title: '确定删除',
        message: `确定删除: ${currentEntity.roleName}(${currentEntity.roleId}) ?`,
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: (action: Action) => {
            if (action === 'confirm') {
                roleApi.remove(currentEntity.roleId!).then(response => {

                    if (response.data.code === 0) {
                        ElMessage.success('删除成功')
                        updateTable();
                    } else {
                        ElMessage.warning('删除失败')
                    }

                });
            }
        }
    });
}


</script>



